package br.com.sales.server;

import br.com.sales.hanserver.action.autocomplete.AutocompleteAction;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Aldo Bernardes Maciel
 */
public class AutocompleteServlet extends HttpServlet {

    private static final long serialVersionUID = -5188855294730126999L;
    private static final List<String[]> data = new ArrayList<>();
    private String lastQuery;
    private String lastTable;
    private JsonArray lastResults;

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException,
            IOException {
        try {
            data.clear();
            JsonArray fullColorArray;
            String query = request.getParameter("q");
            String table = request.getParameter("tableName");
            String attributeDesc = request.getParameter("attributeDesc");
            String attributeID = request.getParameter("attributeID");
            String restriction = request.getParameter("restriction");
            String parameter = request.getParameter("parameter");

            Set<String[]> returnSet = new AutocompleteAction()
                    .getDataByKeyWord(table, attributeDesc, attributeID,
                            query, restriction, parameter);

            for (String[] returnItem : returnSet) {
                data.add(returnItem);
            }

            int count = 0;
            if (query.equals(lastQuery) && lastTable.equals(table)) {
                fullColorArray = lastResults;
                count = lastResults.size();
            } else {
                lastQuery = query;
                lastTable = table;

                fullColorArray = new JsonArray();
                for (String[] colorCode : data) {
                    String colorName = colorCode[0];
                    String lowerColor = colorName.toLowerCase();
                    int has = lowerColor.indexOf(query.toLowerCase());

                    if (!query.isEmpty() && (query.equals("*") || has >= 0)) {
                        try {
                            JsonObject color = new JsonObject();
                            color.addProperty("DisplayName", colorName);
                            color.addProperty("Value", colorCode[1]);
                            fullColorArray.add(color);
                            count++;
                        } catch (Exception ex) {
                            Logger.getLogger(AutocompleteServlet.class.getName()).log(Level.INFO, "Autocomplete - Exception Query error", ex);
                        }
                    }
                }
                lastResults = fullColorArray;
            }

            //get the partial array to be returned
            int indexFrom = Integer.parseInt(request.getParameter("indexFrom"));
            int indexTo = Integer.parseInt(request.getParameter("indexTo"));

            JsonArray partial = new JsonArray();
            if (fullColorArray.size() > 0) {
                int end = count - 1 > indexTo ? indexTo : count - 1;
                for (int i = indexFrom; i <= end; i++) {
                    partial.add(fullColorArray.get(i));
                }
            }

            response.setContentType("application/json");
            PrintWriter out = response.getWriter();

            JsonObject obj = new JsonObject();
            obj.addProperty("TotalSize", count);
            obj.add("Options", partial);
            out.println(obj.toString());

        } catch (NumberFormatException | IOException ex) {
            Logger.getLogger(AutocompleteServlet.class.getName()).log(Level.INFO, "Autocomplete - NumberFormatException | IOException", ex);
        } catch (SQLException ex) {
            Logger.getLogger(AutocompleteServlet.class.getName()).log(Level.INFO, "Autocomplete - Error Search data SQLException", ex);
        }
    }
}
